<template>
  <ContentWrap>
    <el-descriptions :column="3" border>
      <el-descriptions-item label="琴房总数(间)" width="100px">
        {{ formData.roomCount }}
      </el-descriptions-item>
      <el-descriptions-item label="练琴总数(次)" width="100px">
        {{ formData.subCount }}
      </el-descriptions-item>
      <el-descriptions-item label="人均琴房数量(间)" width="100px">
        {{ formData.aveRoom }}
      </el-descriptions-item>

      <el-descriptions-item label="学生总数(人)" width="100px">
        {{ formData.stuCount }}
      </el-descriptions-item>
      <el-descriptions-item label="爽约总数(次)" width="100px">
        {{ formData.brokenCount }}
      </el-descriptions-item>
      <el-descriptions-item label="平均单人时长(分钟)" width="100px">
        {{ formData.aveOneDuration }}
      </el-descriptions-item>

      <el-descriptions-item label="练琴总时长(分钟)" width="100px">
        {{ formData.subDuration }}
      </el-descriptions-item>
      <el-descriptions-item label="取消总数(次)" width="100px">
        {{ formData.cancelCount }}
      </el-descriptions-item>
      <el-descriptions-item label="平均单次练琴时长(分钟)" width="100px">
        {{ formData.aveTimeDuration }}
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>

  <ContentWrap>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px"
             label-width="75px" @submit.native.prevent>
      <el-form-item label="归属学校" prop="schoolId" v-if="tenantId == 1">
        <el-select v-model="queryParams.schoolId" placeholder="请选择" class="!w-240px" filterable
                   default-first-option clearable @change="handleSchoolChange">
          <el-option v-for="item in schools" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="学号/工号" prop="code">
        <el-input v-model="queryParams.code" class="!w-240px" clearable
                  placeholder="请输入学号/工号" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="专业" prop="majorId">
        <el-select v-model="queryParams.majorId" placeholder="请选择专业" clearable>
          <el-option v-for="item in majors" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="当前年级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择年级" clearable>
          <el-option v-for="item in grades" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="学期" prop="term">
        <el-select v-model="queryParams.term" placeholder="请选择学期" clearable>
          <el-option v-for="item in terms" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" class="!w-240px" clearable
                  placeholder="请输入手机号" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh"/>
          重置
        </el-button>
        <el-button v-hasPermi="['yxt:member:create']" plain type="primary"
                   @click="openForm('create')">
          <Icon class="mr-5px" icon="ep:plus"/>
          新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['yxt:member:export']">
          <Icon icon="ep:download"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="学号/工号" prop="code" min-width="120"/>
      <el-table-column label="姓名" prop="name" min-width="100"/>
      <el-table-column label="手机号" prop="mobile" min-width="120"/>
      <el-table-column label="归属学校" prop="schoolName" min-width="100"/>
      <el-table-column label="当前年级" prop="grade">
        <template #default="scope">
          <div> {{ scope.row.type == 0 ? getTermLabel(scope.row.grade, scope.row.term) : '' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="班级" prop="className" min-width="100"/>
      <el-table-column label="专业" prop="majors" min-width="200">
        <template #default="scope">
          <el-tag v-for="tag in scope.row.majors" type="warning" :key="tag"
                  :disable-transitions="true" class="mr-5px">
            {{ tag.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="乐器" prop="musical" min-width="200"/>
      <el-table-column label="练琴总时长(分钟)" prop="totalDuration" min-width="100"/>
      <el-table-column label="预约次数" prop="subCount" min-width="100"/>
      <el-table-column label="爽约次数" prop="brokenCount" min-width="100"/>
      <el-table-column label="取消次数" prop="cancelCount" min-width="100"/>
    </el-table>
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo"
                :total="total" @pagination="getList"/>
  </ContentWrap>
</template>

<script lang="ts" setup>
import {useSubscribeApi} from "@/api/yxt/subscribe";
import {useMajorApi} from "@/api/yxt/major";
import {useConfirm} from "@/components/Notice";
import * as XLSX from 'xlsx/dist/xlsx.full.min'
import {useMessage} from "@/hooks/web/useMessage";
import {getTenantId} from "@/utils/auth";
import {useSchoolApi} from "@/api/yxt/school";

defineOptions({name: 'YxtPractice'})
const tenantId = getTenantId();
const schoolApi = useSchoolApi();
const subScribeApi = useSubscribeApi();
const majorApi = useMajorApi();
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  schoolId: undefined,
  grade: undefined,
  code: undefined,
  majorId: undefined,
  term: undefined,
  mobile: undefined,
  pageNo: 1,
  pageSize: 10,
})
const queryFormRef = ref()
const majors = ref([])
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
}
const schools = ref<Array<any>>([])
const grades = ref([
  {name: "大一", id: 1},
  {name: "大二", id: 2},
  {name: "大三", id: 3},
  {name: "大四", id: 4},
  {name: "已毕业", id: 5}
])
const terms = ref([
  {name: "上学期", id: 1},
  {name: "下学期", id: 2},
])
const formData = ref({
  roomCount: 0,
  stuCount: 0,
  subCount: 0,
  subDuration: 0,
  brokenCount: 0,
  cancelCount: 0,
  aveOneDuration: 0,
  aveRoom: 0,
  aveTimeDuration: 0,
})

const init = async () => {
  let id = queryParams.schoolId;
  if (queryParams.schoolId === undefined) id = 0;
  formData.value = await subScribeApi.subData(id)
}

const getList = async () => {
  loading.value = true
  try {
    const data = await subScribeApi.pageList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleSchoolChange = async (schoolId) => {
  // 根据选择的学校 ID 更新 queryParams
  queryParams.schoolId = schoolId;
  // 重新获取表头统计数据
  // await updateFormData();
};

// 更新表头统计数据的方法
const updateFormData = async () => {
  if (queryParams.schoolId === undefined) {
    formData.value = await subScribeApi.subData(0);
  } else {
    formData.value = await subScribeApi.subData(queryParams.schoolId);
  }
};

const exportLoading = ref(false)
const handleExport = () => {
  useConfirm(t("common.exportMessage"), async () => {
    exportLoading.value = true
    try {
      if (list.value.length == 0) {
        useMessage().warning("没有可导出数据")
      }
      const exportData = multipleSelection.value.length > 0 ? multipleSelection.value
        : await subScribeApi.listNoPage(queryParams);
      const formData = exportData.map(formatData)
      // 创建工作簿
      const wb = XLSX.utils.book_new();
      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(formData);
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, "选中数据");
      // 生成文件
      XLSX.writeFile(wb, "练琴数据.xlsx");
    } finally {
      exportLoading.value = false
    }
  });
}

const formatData = (item: any) => {
  return {
    "学号/工号": item.code,
    "名称": item.name,
    "手机号": item.mobile,
    "归属学校": item.schoolName,
    "当前年级": getTermLabel(item.grade, item.term),
    "班级": item.className,
    "专业": item.majors.map(major => major.name).join(","),
    "乐器": item.musical,
    "练琴总时长": item.totalDuration,
    "预约次数": item.subCount,
    "爽约次数": item.brokenCount,
    "取消次数": item.cancelCount
  }
}

function getTermLabel(grade, term) {
  // 根据 grade 和 term 生成学期标签
  let gradeLabel = '';
  switch (grade) {
    case 1:
      gradeLabel = '大一';
      break;
    case 2:
      gradeLabel = '大二';
      break;
    case 3:
      gradeLabel = '大三';
      break;
    case 4:
      gradeLabel = '大四';
      break;
    case 5:
      gradeLabel = '已毕业';
      break;
    default:
      gradeLabel = '已毕业';
  }
  if (grade == 5) return gradeLabel;
  let termLabel = '';
  switch (term) {
    case 1:
      termLabel = '(上)';
      break;
    case 2:
      termLabel = '(下)';
      break;
    default:
      termLabel = '';
  }
  return gradeLabel + termLabel;
}

const handleQuery = async () => {
  queryParams.pageNo = 1;
  loading.value = true;
  await updateFormData(); // 调用更新表头数据的方法
  await getList(); // 调用获取列表数据的方法
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

onMounted(async () => {
  await init();
  await getList()
  majors.value = await majorApi.getMajorList();
  schools.value = await schoolApi.getSimpleList();

})
</script>
